package com.jake.xpage.route;

import android.content.Context;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.jake.xpage.page.IPageAnimator;
import com.jake.xpage.page.XPage;
import com.jake.xpage.page.XPageContainer;
import com.jake.xpage.router.XPageRoute;
import com.jake.xpage.router.XPageRouteMapper;
import com.jake.xpage.router.XPageRouteMapperManager;
import com.jake.xpage.scheme.XPageSchemeInterceptor;
import com.jake.xpage.scheme.XSchemeInterceptManager;

public class Navigator {
    private static XPageRouteMapperManager sRouteMapperManager;
    private final static XSchemeInterceptManager SCHEME_INTERCEPT_MANAGER = new XSchemeInterceptManager();

    public static void init(@NonNull XPageContainer container) {
        sRouteMapperManager = new XPageRouteMapperManager(new XPageRouteMapper.Callback() {
            @Override
            public Context getContext() {
                return container.getContext();
            }

            @Override
            public void startPage(@NonNull XPage page, @Nullable IPageAnimator animator) {
                if (animator == null) {
                    animator = container.getDefaultAnimator();
                }
                container.startPage(page, animator);
            }
        });

        configRouterMapper(sRouteMapperManager);
        configSchemeIntercept(SCHEME_INTERCEPT_MANAGER);
    }

    private static void configSchemeIntercept(@NonNull XSchemeInterceptManager manager) {
        manager.registerInterceptor(new XPageSchemeInterceptor() {
            @Override
            protected boolean handleRoute(@NonNull XPageRoute route) {
                if (sRouteMapperManager != null) {
                    sRouteMapperManager.openRoute(route);
                    return true;
                }
                return false;
            }
        });
    }

    private static void configRouterMapper(@NonNull XPageRouteMapperManager mapperManager) {
        mapperManager.registerRouteMapper(new DemoRouteMapper());
    }


    public static boolean openUrl(String url) {
        return openUrl(url, null);
    }

    public static boolean openUrl(String url, Object extraObj) {
        return SCHEME_INTERCEPT_MANAGER.handleIntercept(url, extraObj);
    }

}
